#!/usr/bin/perl
use strict;
use warnings;

use Getopt::Long;

sub usage  #<# 
{
    print <<END;
usage: $0 --group <Performance Group> --cores <physical core list>

Required:
-cores <CORELIST> : list of physical cores

Optional:
-h                     : this (help) message
-freq                  : frequency of updates, in ms or s (e.g. 500ms), default: 1s
-group <PERFGROUP>     : Specify what to plot, default FLOPS_DP

Example:
$0 -group FLOPS_DP -cores 0-3 
END

exit(0);
}
#>#

my $CONFIG = {   #<# 
    "FLOPS_DP" => {
        "group" => 'FLOPS_DP',
        "expr" => 'DP MFlops/s',
        "title" => 'Double Precision Flop Rate',
        "yaxis" => 'MFlops/s'},
    "FLOPS_SP" => {
        "group" => 'FLOPS_SP',
        "expr" => 'SP MFlops/s',
        "title" => 'Single Precision Flop Rate',
        "yaxis" => 'MFlops/s'},
    "L2" => {
        "group" => 'L2',
        "expr" => 'L2 bandwidth [MBytes/s]',
        "title" => 'L2 cache bandwidth',
        "yaxis" => 'bandwidth [MB/s]'},
    "L3" => {
        "group" => 'L3',
        "expr" => 'L3 bandwidth [MBytes/s]',
        "title" => 'L3 cache bandwidth',
        "yaxis" => 'bandwidth [MB/s]'},
    "CLOCK" => {
        "group" => 'CLOCK',
        "expr"  => 'Clock [MHz]',
        "title" => 'Clock rate',
        "yaxis" => 'MHz'},
    "NUMA" => {
        "group" => 'MEM',
        "expr" => 'Remote BW [MBytes/s]',
        "title" => 'Remote NUMA bandwidth',
        "yaxis" => 'bandwidth [MB/s]'},
    "MEM" => {
        "group" => 'MEM',
        "expr" => 'MBytes/s',
        "title" => 'Main memory bandwidth',
        "yaxis" => 'bandwidth [MB/s]'}};
#>#

my $FREQ = '1s';
my $CORES = '';
my $optGroup = 'FLOPS_DP';
my $optPlot;

GetOptions ('group=s' => \$optGroup, 'freq=s' => \$FREQ, 'cores=s' => \$CORES, 'plot=s' => \$optPlot, 'help' => \&usage);

my $GROUP = $CONFIG->{$optGroup}->{'group'};
my $yaxis = $CONFIG->{$optGroup}->{'yaxis'};
my $title = $CONFIG->{$optGroup}->{'title'};
my $expr  = $CONFIG->{$optGroup}->{'expr'};
my $legend = '';

open (INPUT, "likwid-perfctr -g $GROUP -d $FREQ -c $CORES |");

select((select(INPUT), $| = 1)[0]);

while (<INPUT>) {
    if (/CORES: ([0-9 ]+)/) {
        my @cores = split ' ',$1;
        my $coreNumber = 0;

        foreach my $core (@cores) {
            $legend .= " --legend $coreNumber=\"core $core\" ";
            $coreNumber++;
        }
        last;
    }
}

open (OUTPUT, "| feedGnuplot --lines  --domain --stream --xlabel \"seconds\" --ylabel \"$yaxis\" --title \"$title\" $legend");

select((select(OUTPUT), $| = 1)[0]);

while (<INPUT>) {
    if (/$expr/) {
        s/$expr//;
        print OUTPUT;
    }
}
close(INPUT);
close(OUTPUT);


# vim: foldmethod=marker foldmarker=#<#,#># 
